import math
import os
import re
import struct
import threading
from collections import defaultdict
from time import sleep

import pandas as pd
import numpy as np
import time
from commen.log import Logger
import openpyxl
import datetime
import commen.config


def ImuDatacontinuity():
    # ---------读取config文件获取筛选字段内容--------------------------
    mpukey = commen.config.global_config.getRaw('keywords', 'suanfaimu')  # [send2Service] [38]
    caninskey = commen.config.global_config.getRaw('keywords', 'cankeyimu')  # Rx 2 0x101

    # ---------读取config文件获取筛选字段内容--------------------------
    logger = Logger(logger='TestMylog').getlog()
    # -----------------------创建excel--------------------------------------------
    # 获取当前时间
    time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
    # 获取当前路径
    result_root = os.getcwd()
    root = os.getcwd()
    result_path = result_root + r'\result' + "\\" + time_now
    log_path = root + r'\original-logfile' + '\\'
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    for root, dirs, files in os.walk(log_path):
        for file in files:
            if "mcu" in file:
                aa = os.path.join(root, file)
            if "can" in file:
                bb = os.path.join(root, file)

    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    book = openpyxl.Workbook()  # 打开一个将写的文件
    sheet = book.create_sheet(index=0)  # 在将写的文件创建sheet
    saveExcel = result_path + "IMU延时验证.xlsx"
    sheet.cell(1, 2).value = "mpu上IMU数据的系统时间T1"
    sheet.cell(1, 3).value = "can上IMU数据系统时间"
    sheet.cell(1, 4).value = "mcu发送IMU数据到can时间T2"
    sheet.cell(1, 5).value = "T2-T1时延"

    row = 1
    # -----------------------创建excel--------------------------------------------

    canfile = open(bb, 'r', encoding='gbk')  # 打开can.log目标文件
    dataprocfile = open(aa, 'r', encoding='UTF-8')  # 打开dataproc.log文件
    logger.info("打开目标文件")
    canlines = canfile.readlines()
    mpulines = dataprocfile.readlines()
    logger.info("获取内容")

    mpusystemtimelist = []  # mpu数据的系统时间T1
    cansystemtimelist = []  # can数据的系统时间
    mpu_utctimelist = []  # mpuutc时间
    can_utctimelist = []  # canutc时间
    mcu_to_can_time = []  # mcu发送IMU数据到can时间T2
    logger.info("开始逐行读取")

    for lines in mpulines:  # 对内容 进行逐行读取

        if mpukey in lines:  # 通过关键字获取数据信息并存入到list中

            # mpusystemtime = lines[:lines.index("<thread")]
            # mpusystemtimelist.append(mpusystemtime.rstrip())
            # mpumessage = lines.split("+0:")
            # mpumessage1 = mpumessage[1].lstrip().replace(" ","").replace("-","").replace("+10:","").replace("+20:","").replace("+30:","").replace("+40:","").replace(")","")
            # mpumessagelist.append(mpumessage1.rstrip())
            # mpu_utctimelist.append(mpumessage1.rstrip()[5:16])

            mpusystemtime = lines[:lines.index("<thread")]
            mpusystemtimelist.append(mpusystemtime.rstrip())
            mpumessage = lines.split("+0:")
            mpumessage1 = mpumessage[1].lstrip().replace(" ", "").replace("-", "").replace("+10:", "").replace("+20:",
                                                                                                               "").replace(
                "+30:", "").replace(")", "")
            year = int(str(mpumessage1[4:6]), 16) + 1970
            month = int(str(mpumessage1[6:8]), 16)
            day = int(str(mpumessage1[8:10]), 16)
            hour = int(str(mpumessage1[10:12]), 16)
            minuet = int(str(mpumessage1[12:14]), 16)
            seconds = int(str(mpumessage1[14:16]), 16)
            millisecond1 = int(str(mpumessage1[16:18]), 16) * 256
            millisecond2 = int(str(mpumessage1[18:20]), 16)
            milliseconds = int(millisecond1) + int(millisecond2)
            # --------------------截取代表mcu数据时间的16进制内容并转换成时间-----------------------------
            if month < 10:
                month = "0" + str(month)
            if day < 10:
                day = "0" + str(day)
            if hour < 10:
                hour = "0" + str(hour)
            if minuet < 10:
                minuet = "0" + str(minuet)
            if seconds < 10:
                seconds = "0" + str(seconds)
            if milliseconds < 10:
                milliseconds = "00" + str(milliseconds)
            if 10 <= int(milliseconds) < 100:
                milliseconds = "0" + str(milliseconds)
            # ---------------------------判断时间是否是矫正前的1970年----------------------------------------
            if int(str(mpumessage1[4:6]), 16) == 0:
                mcutime = "1980" + "-" + "01" + "-" + "06" + " " + "00" + ":" + "00" + ":" + str(
                    seconds) + "." + str(
                    milliseconds)
                # sheet.cell(row, 2).value = mcutime



            # --------------------------------拼接矫正前的1970年时间并写入----------------------------------------
            # -----------------------------------------拼接矫正后的时间并写入----------------------------------------
            else:
                mcutime = str(year) + "-" + str(month) + "-" + str(day) + " " + str(hour) + ":" + str(
                    minuet) + ":" + str(
                    seconds) + "." + str(
                    milliseconds)
            mpu_utctimelist.append(mcutime)

            # utc时间：str(mpumessage1.rstrip()[5:7])+" "+str(mpumessage1.rstrip()[7:9])+" "+str(mpumessage1.rstrip()[9:11])+" "+str(mpumessage1.rstrip()[11:13])+" "+str(mpumessage1.rstrip()[13:15])
    for canline in canlines:  # 对内容 进行逐行读取
        if caninskey in canline:  # 通过关键字获取数据信息并存入到list中
            systemtime = canline[:canline.index("Rx")]
            cansystemtimelist.append(systemtime.rstrip())
            canmessage = canline.split("s-fd-brs 64")
            mcu_to_can_time.append(canmessage[1].replace(" ", "").rstrip()[-12:-1])
            receivetime_old = bin(int(str(canmessage[1].replace(" ", "")[46:57]), 16))  # 十进制字符串转换成二进制
            # -------------------------二进制字符串转换成整数并拼接成时间------------------------------------
            try:

                year = pd.to_datetime("1980-01-06") + pd.DateOffset(days=int(receivetime_old[0:16], 2))
                year = year.strftime('%Y-%m-%d')
                hour = str(int(receivetime_old[16:22], 2))
                minute = str(int(receivetime_old[22:28], 2))
                seconds = str(int(receivetime_old[28:34], 2))
                milliseconds = str(int(receivetime_old[34:], 2))
                if int(hour) < 10:
                    hour = "0" + str(hour)
                if int(minute) < 10:
                    minute = "0" + str(minute)
                if int(seconds) < 10:
                    seconds = "0" + str(seconds)
                if int(milliseconds) < 10:
                    milliseconds = "00" + str(milliseconds)
                if 10 <= int(milliseconds) < 100:
                    milliseconds = "0" + str(milliseconds)
                sf_receivetime = year + " " + hour + ":" + minute + ":" + seconds + "." + milliseconds
                can_utctimelist.append(sf_receivetime)
            except:
                continue
    for i in mpu_utctimelist:

        if i in can_utctimelist:
            logger.info("开始进行对比")
            row = row + 1
            mpu_number = mpu_utctimelist.index(str(i))
            can_number = can_utctimelist.index(str(i))
            t1 = datetime.datetime.strptime(mpusystemtimelist[mpu_number], '%Y-%m-%d %H:%M:%S.%f')
            try:

                if mcu_to_can_time[can_number] == 0:
                    continue
                # todo: 这个判断永远为false，全0字符串，二进制0b0转换报错
                receivetime_old = bin(int(mcu_to_can_time[can_number], 16))  # 十进制字符串转换成二进制
                # -------------------------二进制字符串转换成整数并拼接成时间------------------------------------

                year = pd.to_datetime("1980-01-06") + pd.DateOffset(days=int(receivetime_old[0:16], 2))
                year = year.strftime('%Y-%m-%d')
                hour = str(int(receivetime_old[16:22], 2))
                minute = str(int(receivetime_old[22:28], 2))
                seconds = str(int(receivetime_old[28:34], 2))
                milliseconds = str(int(receivetime_old[34:], 2))
                if int(hour) < 10:
                    hour = "0" + str(hour)
                if int(minute) < 10:
                    minute = "0" + str(minute)
                if int(seconds) < 10:
                    seconds = "0" + str(seconds)
                if int(milliseconds) < 10:
                    milliseconds = "00" + str(milliseconds)
                if 10 <= int(milliseconds) < 100:
                    milliseconds = "0" + str(milliseconds)
                sf_receivetime = year + " " + hour + ":" + minute + ":" + seconds + "." + milliseconds
            except:
                sheet.cell(row, 2).value = mpusystemtimelist[mpu_number]
                sheet.cell(row, 3).value = cansystemtimelist[can_number]
                sheet.cell(row, 4).value = mcu_to_can_time[can_number]
                sheet.cell(row, 5).value = "输出到can上时间异常"
                continue
            t2 = datetime.datetime.strptime(sf_receivetime, '%Y-%m-%d %H:%M:%S.%f')
            sheet.cell(row, 2).value = mpusystemtimelist[mpu_number]
            sheet.cell(row, 3).value = cansystemtimelist[can_number]
            sheet.cell(row, 4).value = sf_receivetime
            try:

                t1 = int(time.mktime(t1.timetuple()) * 1000.0 + t1.microsecond / 1000.0)
                t2 = int(time.mktime(t2.timetuple()) * 1000.0 + t2.microsecond / 1000.0)
                deltat = int(t2) - int(t1)
                sheet.cell(row, 5).value = deltat
            except:
                sheet.cell(row, 5).value = str(int((t2 - t1).microseconds / 1000))

    # ----------------------将对比的数据写入excel---------------------------------
    book.save(saveExcel)
    # ----------------------将对比的数据写入excel---------------------------------


ImuDatacontinuity()
